﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;

namespace Sustainalytics.GCCS.DataAccessLayer
{
    public class RPDbContext : IRPDbContext
    {
        private readonly SqlDatabase _database;
        private readonly int _commandTimeout;

        public RPDbContext()
        {
            _commandTimeout = 60 * 60;
        }

        public RPDbContext(string connectionString, int commandTimeout)
        {
            if (string.IsNullOrEmpty(connectionString))
                throw new Exception("Connection string must be provided!");

            _database = new SqlDatabase(connectionString);
            _commandTimeout = commandTimeout;
        }

        public IDataReader CompanyProfiles(List<Guid> companyIds)
        {
            var command = new SqlCommand
            {
                CommandText = "spGetCompanyProfilesByCompanyIds",
                CommandType = CommandType.StoredProcedure,
                CommandTimeout = _commandTimeout
            };

            var ids = new XElement("CompanyIds", companyIds.Select(id => new XElement("Id", id)));

            command.Parameters.AddWithValue("@CompanyIds", ids.ToString());

            return _database.ExecuteReader(command);
        }
    }
}
